package org.example.bighomework.Teacher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Controller
@RequestMapping("/Teacher")
public class TeacherController {
    @Autowired
    private TeacherService teacherService;
    //主页
    @GetMapping("/")
    public String viewHomePage(Model model){
        return findPaginated(1, "name", "asc", model);
    }
    //增加
    @GetMapping("/showTeacherForm")
    public String showTeacherForm(Model model) {
        Teacher teacher = new Teacher();
        model.addAttribute("teacher", teacher);
        return "new_teacher";
    }
    //保存和更新
    @PostMapping("/saveTeacher")
    public String saveTeacher(@ModelAttribute("teacher") Teacher teacher) {
        teacherService.saveTeacher(teacher);
        return "redirect:/Teacher/";
    }

    @GetMapping("/showFormForUpdate/{id}")
    public String showFormForUpdate(@PathVariable(value = "id") String id, Model model) {
        Teacher teacher = teacherService.getTeacherById(id);
        model.addAttribute("teacher", teacher);
        return "update_teacher";
    }
    //删除
    @GetMapping("/deleteTeacher/{id}")
    public String deleteTeacher(@PathVariable(value = "id") String id) {
        this.teacherService.deleteTeacherById(id);
        return "redirect:/Teacher/";
    }
    //按教师姓名查询
    @GetMapping("/query{Name}")
    public String query(@PathVariable(value = "Name") String Name, Model model) {
        List<Teacher> listTeacher = teacherService.findByName(Name);
        model.addAttribute("listTeacher", listTeacher);
        return "TeacherIndex";
    }
    //获取分页数据
    @GetMapping("/page/{pageNo}")
    public String findPaginated(@PathVariable(value = "pageNo") int pageNo,
                                @RequestParam("sortField") String sortField,
                                @RequestParam("sortDir") String sortDir,
                                Model model) {
        int pageSize = 3;
        Page<Teacher> page = teacherService.findPaginated(pageNo, pageSize, sortField, sortDir);
        List<Teacher> listTeacher = page.getContent();
        model.addAttribute("currentPage", pageNo);
        model.addAttribute("totalPages", page.getTotalPages());
        model.addAttribute("totalItems", page.getTotalElements());
        model.addAttribute("sortField", sortField);
        model.addAttribute("sortDir", sortDir);
        model.addAttribute("reverseSortDir", sortDir.equals("asc") ? "desc" : "asc");
        model.addAttribute("listTeacher", listTeacher);
        return "TeacherIndex";
    }
}
